//set working directory 
cd  "C:\Users\johna\Dropbox (Curiel Analytx)\ElectionNightResults\replication_code"


//read in the state dta file 
use "data\nyt_states.dta", clear
sort state time
drop total // Don't need this.  We'll generate two-party total later

*** Calculate when Biden or Trump were certain to win

** Note:  for now, we had to fudge the total number of votes, because there are
** times when the reported vote totals exceed the number of votes Leip reports

egen max_leip_tvotes = max(leip_tvotes),by(state)
egen max_total = max(total), by(state)

egen rowmax_tvotes_total = rowmax(max_leip_tvotes max_total)


gen final_D = .5*leip_tvotes
gen D_needpct = 100*(final_D - dem)/(rowmax_tvotes_total - dem - rep)
gen left = 100*(final_D - dem)
gen right = (rowmax_tvotes - dem - rep)

replace norm_total = 100*(dem + rep)/rowmax_tvotes_total

keep if state == "michigan"
replace D_needpct = 0 if D_needpct < 0
sort norm_total

twoway (line dempct hoursfromclose if time_num > time_num[_n-1] | _n == 1, connect(stairstep)) ///
       (line D_needpct hoursfromclose if time_num > time_num[_n-1] | _n == 1, lcolor(medsl_blue4) lpattern(dash) connect(stairstep)) ///
	   (line norm_total hoursfromclose if time_num > time_num[_n-1] | _n == 1, lcolor(medsl_gold) lpattern(shortdash) connect(stairstep)) ///
	   if hoursfromclose <= 50 ///
	   , ///
	   ylabel(0 10 20 30 40 50 60 70 80 90 100 "100%", labsize(small)) ///
	   xlabel(0(6)48,labsize(small)) ///
	   xtitle(Hours from poll closing) ///
	   legend(order(3 "Ballots reported"  1 "Reported for Biden" 2 "Unreported ballots needed for Biden win") size(vsmall)) ///
	   text(3 25 "Unreported ballots needed for Biden win is < 0% from here onward.",size(*.5) just(left) placement(3))
graph export "figures\fig7.png", replace width(2500)	   

